package server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class MyTestDecoder extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf b= (ByteBuf)msg;
        byte[] bytes = new byte[b.readableBytes()];
        b.getBytes(0,bytes);
        String s1 = Byte2String(bytes);
        System.out.println(s1);
        //去下一个
        super.channelRead(ctx, msg);
    }

    /**
     * 字节数组转二进制
     * @param nByte
     * @return
     */
    public String Byte2String(byte[] nByte){
        StringBuilder s=new StringBuilder();
        for (byte b : nByte) {
            StringBuilder nStr=new StringBuilder();
            for(int i=7;i>=0;i--){
                int j=(int)b & (int)(Math.pow(2, (double)i));
                if(j>0){
                    nStr.append("1");
                }else {
                    nStr.append("0");
                }
            }
            s.append(nStr);
            s.append(" ");
        }
      return s.toString();
//        StringBuilder nStr=new StringBuilder();
//        for(int i=7;i>=0;i--){
//            int j=(int)nByte & (int)(Math.pow(2, (double)i));
//            if(j>0){
//                nStr.append("1");
//            }else {
//                nStr.append("0");
//            }
//        }
//        return nStr.toString();

    }


    /**
     * 字节数组转16进制
     * @param bArray
     * @return
     */
    public String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }


}

